<template>
  <div>
    <a-button v-if="showBtn" @click="visible=true">
      <i class="fa fa-sort-numeric-asc mr5"></i>排序
    </a-button>
    <a-drawer
      :title="title"
      width="30%"
      placement="right"
      :closable="false"
      :visible="visible"
      @close="visible=false"
    >
      <div class="pos-rlt">
        <div class="pos-abs r0" style="top:-70px;">
          <a-button v-if="result.length>0" type="primary" @click="save">保存</a-button>
        </div>
        <draggable
          v-model="items"
          chosenClass="chosen"
          forceFallback="true"
          group="module"
          animation="1000"
          @start="onStart"
          @end="onEnd">
          <transition-group>
            <div class="item" v-for="(t,i) in items" :key="`obj${i}`">{{ t.name }}</div>
          </transition-group>
        </draggable>
        <div v-if="saving" class="tac pd10" style="color:#555;"><a-spin class="mr10" />正在保存序号...</div>
      </div>
    </a-drawer>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
export default {
  components: {
    draggable
  },
  props: {
    title: {
      type: String,
      default: '数据排序'
    },
    showBtn: {
      type: Boolean,
      default: true
    },
    list: {
      type: Array,
      default: () => {
        return [{ name: 'aaaa' }, { name: 'bbbb' }, { name: 'cccc' }, { name: 'dddd' }]
      }
    }
  },
  data () {
    return {
      visible: false,
      saving: false,
      items: this.list,
      result: []
    }
  },
  methods: {
    open (list) {
      this.items = list || []
      this.visible = true
    },
    close () {
      this.visible = false
    },
    onStart () {},
    onEnd () {
      this.saving = true
      setTimeout(() => {
        this.saving = false
        this.result = this.items.map((t, i) => {
          t.index = i
          return t
        })
        this.$emit('sort', this.result)
      }, 200)
    },
    save () {
      this.$emit('ok', this.result)
    }
  }
}
</script>
<style lang="less" scoped>
  .item{
    padding:10px;
    border:solid 1px #b8e7f5;
    background:#b8e7f5;
    color:#555;
    margin-bottom:10px;
    border-radius:4px;
    cursor:move;
  }
  .chosen{
    border:solid 1px #096daf;
    background:#096daf;
    color:#fff;
  }
</style>
